
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <vector>
#include <map>
#include "pub.h"
#include "nqlog.h"

#ifdef __linux__
#include <signal.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <linux/if_packet.h>
#include <netinet/if_ether.h>
#include <netinet/in.h> 
#include <arpa/inet.h>
#elif _WIN32
#include <WinSock2.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")
#endif

#define NQ_LOG  "./NQ.log"
#define NQ_MAXCNT  (1000000)

UINT nqlog_count;
FILE *result_log;

NQResult::NQResult()
{
    nq_type = 0;
    nq_sip= 0;
    nq_sport = 0;
    nq_dip = 0;
    nq_dport = 0;
    nq_dnsip = 0;
    memset(nq_name, 0, sizeof(nq_name));
}

void NQ_ret_open(void)
{
    remove(NQ_LOG);
    result_log = fopen(NQ_LOG, "a+");
    setbuf(result_log, NULL);
    return ;
}

#if 0
void NQ_ret_close(void)
{
    fclose(result_log);
    result_log = NULL;
    return ;
}
#endif

void NQ_ret_writelog(NQResult& rs)
{
    char s_sip[32] = { 0 };
    char s_dip[32] = { 0 };
    char s_dnsip[32] = { 0 };
    char s_time[64] = { 0 };
    struct tm* local = NULL;
    time_t current = time(NULL);
    
    if ((!result_log) || (nqlog_count > NQ_MAXCNT))
    {
        return ;
    }

    local = localtime(&current);
    sprintf(s_time, "%04d-%02d-%02d %02d:%02d:%02d",
            local->tm_year+1900, local->tm_mon, local->tm_mday,
            local->tm_hour, local->tm_hour, local->tm_sec);

    nqlog_count++;
    strcpy(s_sip, NQ_IPSTR(rs.nq_sip));
    strcpy(s_dip, NQ_IPSTR(rs.nq_dip));
    strcpy(s_dnsip, NQ_IPSTR(rs.nq_dnsip));
    fprintf(result_log, "%u,%u,%s,%u,%s,%u,%s,%s,%s\n",
            nqlog_count, rs.nq_type, s_sip, rs.nq_sport,
            s_dip, rs.nq_dport, rs.nq_name, s_dnsip, s_time);
    fflush(result_log);

    return ;
}

void NQ_ret_write(NQResult& rs)
{
    if (!result_log)
    {
        NQ_ret_open();
    }

    NQ_ret_writelog(rs);
}
